package h_10_27;

/**
 * 1658. 将 x 减到 0 的最小操作数
 * https://leetcode.cn/problems/minimum-operations-to-reduce-x-to-zero/description/
 */
public class Main3 {
    public int minOperations(int[] nums, int x) {
        int n = nums.length;
        int left = 0;
        int right = 0;
        int sum = 0;
        int ret = -1;
        for(int i = 0;i < n;i++) {
            sum += nums[i];
        }
        // 求 sum - x 后的值，最长的长度，之后总长度减去 这个长度 即是最后需要的值
        int t = sum - x;
        if(t < 0) {
            return -1;
        }
        int sumMax = 0;
        while(right < n) {
            int in = nums[right];
            sumMax += in;

            while(sumMax > t) {
                sumMax -= nums[left++];
            }

            if(sumMax == t) {
                ret = Math.max(ret,right - left + 1);
            }
            right++;
        }
        return ret == -1 ? ret : n - ret;
    }
}
